#include<iostream>
#include<string>
#include<unistd.h>
#include<cstdio>
#include"Thread.hpp"


int ticket=10000;
std::string GetThreadName()
{
    static int number=1;
    char name[64];
    snprintf(name,sizeof name, "Thread - %d",number++);
    return name;
}
void GetTicket(pthread_mutex_t*mutex)
{
    while(true)
    {
    pthread_mutex_lock(mutex);
    if(ticket>0)
    {
        usleep(1000);
        std::cout<<"get a ticket "<<ticket--<<std::endl;
        pthread_mutex_unlock(mutex);
    }
    else
    {
        pthread_mutex_unlock(mutex);
        break;
    }
    }
}

int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
    std::string name1 = GetThreadName();
    Thread<pthread_mutex_t *> t1(name1, GetTicket, &mutex);

    std::string name2 = GetThreadName();
    Thread<pthread_mutex_t *> t2(name2, GetTicket, &mutex);

    std::string name3 = GetThreadName();
    Thread<pthread_mutex_t *> t3(name3, GetTicket, &mutex);

    std::string name4 = GetThreadName();
    Thread<pthread_mutex_t *> t4(name4, GetTicket, &mutex);

    t1.Start();
    t2.Start();
    t3.Start();
    t4.Start();

    t1.Join();
    t2.Join();
    t3.Join();
    t4.Join();
    pthread_mutex_destroy(&mutex);
    return 0;
}